package com.ruoyi.web.controller.system;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.mail.EmailUtils;
import com.ruoyi.common.mail.MailLoginBody;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.service.SysEmailLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.SecureRandom;

@RestController
@RequestMapping("/email")
public class EmailLoginController {

    @Autowired
    private EmailUtils emailUtils;
    @Autowired
    private SysEmailLoginService sysEmailLoginService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 登录方法
     *
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody MailLoginBody mailLoginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = sysEmailLoginService.login(mailLoginBody.getEmail(), mailLoginBody.getCode());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @GetMapping("/sendLoginCode")
    public AjaxResult sendLoginCode(@RequestParam String to) {
        // 生成 [100000, 999999] 范围内的随机数
        SecureRandom secureRandom = new SecureRandom();
        String code = String.valueOf(100000 + secureRandom.nextInt(900000));

        String verifyKey = "email-login-code:" + to;
        redisCache.setCacheObject(verifyKey, code);

        emailUtils.sendSimpleEmail(to, "登录验证码", code);

        return AjaxResult.success("验证码发送成功！");
    }
}